﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Net;
using System.IO;
using System.Diagnostics;
using DoubanApiLib.Base;


namespace DoubanApiLib.OAuth
{
    public class OAuthWork
    {

        internal static OAuthBase oAuth;

        static OAuthWork()
        {

            oAuth = new OAuthBase();
        }



        public string RequestToken
        {
            get;
            set;
        }
        public string RequestTokenSecret
        {
            get;
            set;
        }

        /// <summary>
        /// 获取用户确认授权Url
        /// </summary>
        public string GetUserAuthorizationUrl()
        {
            Dictionary<string, string> responseValues = null;
            Uri requestTokenUri = new Uri(Runtime.Api.OAuth.RequestTokenURI);
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;

            // 签名
            string sig = oAuth.GenerateSignature(
                requestTokenUri,
                Runtime.SystemParam.API_KEY,
                Runtime.SystemParam.API_KEY_SECRET,
                string.Empty,
                string.Empty,
                "GET",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1,
                out normalizeUrl,
                out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            StringBuilder sb = new StringBuilder(requestTokenUri.ToString());
            sb.AppendFormat(Runtime.Api.OAuth.RequestTokenURI_PARAM,
                            Runtime.SystemParam.API_KEY, nonce, timeStamp, "HMAC-SHA1", "1.0", sig);

            Runtime.Debug.WriteLine("请求Request Token的url: \n" + sb.ToString());
            //请求Request Token
            string responseBody = HttpHelper.SendRequestWithNoData(sb.ToString());
            Runtime.Debug.WriteLine("请求Request Token的返回值: \n" + responseBody);
            responseValues = Until.ParseResponse(responseBody);
            RequestToken = responseValues["oauth_token"];
            RequestTokenSecret = responseValues["oauth_token_secret"];

            //生成引导用户授权的url
            string url = (Runtime.Api.OAuth.AuthorizationURI + Runtime.Api.OAuth.AuthorizationURI_PARAM).FormatMe(RequestToken);
            return url;
        }

        /// <summary>
        /// 设置绑定账号
        /// </summary>
        public bool GetAccountAccessToken(out string userId, out string accessToken, out string accessTokenSecret)
        {
            try
            {
                Dictionary<string, string> responseValues;
                Uri uri = new Uri(Runtime.Api.OAuth.AccessTokenURI);
                string nonce = oAuth.GenerateNonce();
                string timeStamp = oAuth.GenerateTimeStamp();
                string normalizeUrl, normalizedRequestParameters;

                // 签名
                string sig = oAuth.GenerateSignature(
                    uri,
                    Runtime.SystemParam.API_KEY,
                    Runtime.SystemParam.API_KEY_SECRET,
                    this.RequestToken,
                     this.RequestTokenSecret,
                    "GET",
                    timeStamp,
                    nonce,
                    OAuthBase.SignatureTypes.HMACSHA1,
                    out normalizeUrl,
                    out normalizedRequestParameters);
                sig = HttpUtility.UrlEncode(sig);

                StringBuilder sb = new StringBuilder(uri.ToString());
                sb.AppendFormat(Runtime.Api.OAuth.AccessTokenURI_PARAM,
                                Runtime.SystemParam.API_KEY, nonce, timeStamp, "HMAC-SHA1", "1.0", sig, this.RequestToken);

                string responseBody = HttpHelper.SendRequestWithNoData(sb.ToString());
                responseValues = Until.ParseResponse(responseBody);
                accessToken = responseValues["oauth_token"];
                accessTokenSecret = responseValues["oauth_token_secret"];
                userId = responseValues["douban_user_id"];
            }
            catch
            {
                accessToken = accessTokenSecret = userId = Runtime.MessageParam.UNDEFINE;
                return false;
            }

            return true;
        }





    }
}
